你能用c++在一行中初始化一个指针和相应的对象吗


class test {
public:
int& n;
test(int& n) : n(n) {}
};
int main() {
test* ptr = ptr(3); // something like this and 3 
// should be a variable as pointed out in the comments
}

你能在一行中初始化一个指针和它指向的对象吗?

是。

class test {
public:
int& n;
test(int& n) : n(n) {}
};
int main() {
int value = 3;
test obj(value), *ptr = &obj;
}

注意,int& n不能接受像3那样的文字。

另一种选择是使用new在堆上创建一个对象。

class test {
public:
int& n;
test(int& n) : n(n) {}
};
int main() {
int value = 3;
test *ptr = new test(value); // create an object
delete ptr; // delete the object
}

最新更新