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
}