I am new to C++. How do you create a method within one class which initializes an object within another class with specified parameters? Something like the following.
class A {
public:
double X;
double Y;
A(double a, double b) {
X = a;
Y = b;
};
class B {
public:
A f(double a, double b) {
//Initialize an object of type A using parameters specified.
};
};
I want to use the object of type A later so, presumably, I would need to use the new operator within f. Thanks in advance.
Try this:
class B {
public:
A* f(double a, double b) { return new A(a, b); };
};
Although you could just as easily do new A(a,b) anywhere you wanted to do B.f(a,b).
Related
For Dart 2.17, we can use constructors in enum similarly to how we do with classes.
I am trying to insert an anonymous function inside of an enum directly.
here is code that works but doesn't do exactly what I'd like it to do.
int _add(int a, int b) => a + b;
int _sub(int a, int b) => a - b;
int _mul(int a, int b) => a * b;
double _div(int a, int b) => a / b;
enum MyEnum {
addition(_add),
subtract(_sub),
multiplication(_mul),
division(_div);
final Function fx;
const MyEnum(this.fx);
}
void main() {
var fun = MyEnum.addition;
print(fun.fx(1, 2));
fun = MyEnum.subtract;
print(fun.fx(1, 2));
fun = MyEnum.multiplication;
print(fun.fx(1, 2));
fun = MyEnum.division;
print(fun.fx(1, 2));
}
Instead of making a function somewhere else in the code, as the _add, _sub, _mul, _div, I would like to directly insert an anonymous function into the enum, like in the following code (please note that the following code does not work).
What I'd like to do
enum MyEnum {
// I'd like to insert an anonymous function instead.
addition((int a, int b) => _add(a, b)),
subtract((int a, int b) => a - b),
multiplication(int a, int b) => a * b),
division((int a, int b) => a / b;);
final Function fx;
const MyEnum(this.fx);
}
Is it possible? Would anyone be able to show me how to do this? I cannot figure out what I am doing wrong.
One point of Dart 2.17 is that you no longer need to use extensions. The following code, which incorporates the features of Dart 2.17, is how I solved it. Though this certainly is not as elegant nor satisfying as I would have hoped it would have been in my original post.
enum MyEnum {
addition(),
subtract(),
multiplication(),
division();
Function fx() {
switch (this) {
case addition:
return (int a, int b) => a + b;
case subtract:
return (int a, int b) => a - b;
case multiplication:
return (int a, int b) => a * b;
case division:
return (int a, int b) => a / b;
default:
throw Exception('Unknown operation');
}
}
const MyEnum();
}
void main() {
var fun = MyEnum.addition;
print(fun.fx()(1, 2));
fun = MyEnum.subtract;
print(fun.fx()(1, 2));
fun = MyEnum.multiplication;
print(fun.fx()(1, 2));
fun = MyEnum.division;
print(fun.fx()(1, 2));
}
Have you tried extensions? I'm not sure you'll be able to do everything you want (as happened to me), but they almost got the job done. Sometimes I just have to invoke the extension instead of the enum, probably when I put some static method on the extension (like calling SexExt.staticMethod() instead of Sex.staticMethod), but I find them pretty useful.
enum Sex { MALE, FEMALE }
extension SexExt on Sex {
String getText() {
switch (this) {
case Sex.MALE:
return "Maschio";
case Sex.FEMALE:
return "Femmina";
}
}
String getShortText() {
switch (this) {
case Sex.MALE:
return "M";
case Sex.FEMALE:
return "F";
}
}
}
class Foo {
Foo(int y);
}
class Bar extends Foo {
int value;
Bar(int x) { // error in this line
value = x;
print("Hi there");
super(x); // error in this line
}
}
How can I call super inside constructor body?
Note:
I know I can use initialiser list to solve it but I would like to know how to call super inside method body?
Bar(int x): value = x, super(x); // works but I am not looking for it.
Dart does not support inheriting the constructors as explicitly callable methods. The initializer list you mentioned is the supported way to call unnamed super constructors in Dart.
However, you can achieve what you want with the help of named constructors. Take a look at the below example -
class Foo {
int superValue;
Foo(); //A default zero-argument constructor
Foo._init(this.superValue); //Named constructor
void initValue(int x) => Foo._init(x);
}
class Bar extends Foo {
int value;
Bar(int x) {
value = x;
print("Hi there");
super.initValue(x);
}
}
void main() {
Foo foo = Bar(10); //prints 'Hi there'
}
Hope it helps!
UPDATE
You can also call the super constructor and add other statements to the child constructor using this way -
class Foo {
int superValue;
Foo(this.superValue);
}
class Bar extends Foo {
int value;
Bar(int x) : super(x) {
value = x;
print("Hi there");
}
}
void main() {
Foo foo = Bar(10);
}
Is it possible to define implicit casts for classes?
For instance, I have a class Color:
class Color {
public var r: Int;
public var g: Int;
public var b: Int;
public function new(?r: Int = 0, ?g: Int = 0, ?b: Int = 0) {
this.r = r;
this.g = g;
this.b = b;
}
}
If I have a Array<Int> like this:
var myIntegerArray = [255, 0, 255]; // color written in RGB as an array
var c: Color = myIntegerArray; // <= how to make this possible?
trace(c.r);
I tried #:from on a static function in my class:
#:from
static public function fromArray(a: Array<Int>) {
return new Color(a[0], a[1], a[2]);
}
but the compiler is still not happy about this (Error: Array<Int> should be Color).
I know I could just use the static function like var c = Color.fromArray(myIntegerArray); but I'm curious whether or not it is possible to implicitly cast it.
No, implicit cast for normal class is impossible. But you have three solutions:
Create abstract Color(Array<Int>) instead class;
Use "chain" e.g. class Color > abstract ColorAbs > Array<Int>;
Use haxe.extern.EitherType<Color, Array<Int>>;
I don't recommend the second solution.
I'm having some trouble with deriving a pointer to a derived class. I think it has something to do with a constructor. Do I have to create a new constructor in my derived class? How to I create a pointer from a derived class? Thanks
Class Base
{
public:
int myfunction(int a,int b,int c)
{
return a+b+c;
}
};
Class Derived: public Base
{
int newfunction(int a, int b, int c)
{
return a*b*c;
};
};
int main()
{
// this doesn't work at all.. I get all errors every time I try to refer to the object
//instantiated from my derived class.
//I know it's my lack of understanding.
Derived *NewObject = new Derived;
//Why wont this work?
}
C++ is case sensitive, and the keyword class is lowercase. You wrote Class for both classes, and it looks like it's the only issue with your code.
please explain me how this code is working and why it will trough an error in class B
public class A
{
protected int x;
static void F(A a, B b) {
a.x = 1; // Ok
b.x = 1; // Ok
}
}
public class B: A
{
static void F(A a, B b) {
a.x = 1; // Error, must access through instance of B
b.x = 1; // Ok
}
}
Code in B can only access a protected variable through an expression which has a compile-time type of B or some type derived from B. That's basically how protected access works.
From section 3.5.3 of the C# 4 language specification:
When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.
The protected keyword is a member
access modifier. A protected member
is accessible from within the class in
which it is declared, and from within
any class derived from the class
that declared this member.
public class A
{
public int x;
public static void F(A a, B b)
{
a.x = 1;
b.x = 1;
}
}
public class B : A
{
public static void F(A a, B b)
{
a.x = 1;
b.x = 1;
}
}
Why I redefined it with public access modifier. protected modifier has restricted access to inherit class blocks.
Class A {
protected int x = 0;
}
Class B : A {
private void SomeFunc() {
Console.WriteLine(this.x.ToString()); // This will work!
}
}
But if you try to access x you'll get nothing in B.
B b = new B();
b.x; // Got nothing in IntelliSense
See we got the access of x in a function of B but it's instance has no access of x.