正如你所看到的,我是C++的新手,但我无法理解为什么y = new Person()函数foo是错误的.谢谢你的帮助.
我收到这个错误:
错误:'y =(((Person*)operator new(32u)),(,)中的'operator ='不匹配)''
我将接受今晚最赞成的答案或更有说服力的答案.
我和我的朋友之间的争论是foo函数可以改变对象并在函数之外传播更改,就像在做的时候一样y = Person(),然后brother也会改变它还是会保持原样?
.
#include <iostream>
using namespace std;
class Person {
public:
int age;
char name[25];
Person() {
age = 0;
}
};
void foo(Person &y)
{
y = new Person();
}
int main()
{
Person *brother = new Person();
brother->age = 20;
cout << "age = " << brother->age << endl;
foo(*brother);
cout << "age = " << brother->age << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你可能来自一种语言,对象只能用new创建.在C++中,情况并非如此.除非你真的需要它,否则你不应该使用新的.只需将其创建为普通变量:
#include <iostream>
#include <string>
class Person
{
public:
unsigned age;
std::string name;
Person(unsigned age, std::string name)
: age(age)
, name(std::move(name)) // move is C++11
{}
};
int main()
{
Person brother(8, "Tim John");
std::cout << "age = " << brother.age << '\n';
// Edit regarding the question in the comments:
brother = Person(16, "John Tim");
std::cout << "age = " << brother.age << '\n';
}
Run Code Online (Sandbox Code Playgroud)
你上面代码的问题是new返回一个指针,你试图分配一个指向Person的指针,这显然是行不通的.