【发布时间】:2014-12-19 09:44:34
【问题描述】:
大家好,我找不到为动态分配的对象构建合适的复制构造函数的方法。它大喊:error: no matching function for call to 'Person::(Person*&')
我的测试代码是这样的:
#include <iostream>
#include <cstring>
class Person
{
private:
int* age;
std::string name;
public:
Person(std::string name_in, int age_in);
Person(const Person& other);
~Person();
void printAge();
void printName();
};
Person::Person(std::string name_in, int age_in)
{
std::cout << "Creating person named " << name_in << std::endl;
name = name_in;
age = new int;
*age = age_in;
}
Person::Person(const Person& other)
{
std::cout << "Copying person." << std::endl;
age = new int;
*age = *other.age;
name = other.name;
}
Person::~Person()
{
std::cout << "Freeing memory!" << std::endl;
delete age;
}
void Person::printAge()
{
std::cout << "The age is " << *age << std::endl;
}
void Person::printName()
{
std::cout << "The name is " << name << std::endl;
}
int main()
{
Person* person1 = new Person("Ramon", 19);
person1->printAge();
person1->printName();
Person* person2 = new Person(person1);
person2->printAge();
person2->printName();
delete person1;
delete person2;
return 0;
}
似乎在创建 person2 对象时它只是指向 person1 的指针,但事实并非如此!我声明它是一个新的动态分配对象:Person* person1 = new Person("Ramon", 19);。知道这可能是什么原因吗?
谢谢。
【问题讨论】:
-
为什么要动态分配年龄?复制构造函数需要一个引用,而不是一个指针,所以你需要
Person(*person1)。你的赋值运算符呢?但是,如果您没有使用年龄指针,则不需要任何自定义复制构造函数,并且它会很好地复制。您不需要在此代码中添加任何新内容或删除内容。 -
Person* person2 = new Person(* /* <<< dereference */ person1); -
@NeilKirk 是的,你是对的,但我正在开发一个更大规模的程序,需要将我的问题转化为一个简单的版本,而且我很糟糕创建明智的例子,你可以看到哈哈我将尝试传递引用而不是指针。谢谢。
-
哦,是的,你是对的!我需要通过引用传递才能复制。抱歉,我不知道。
-
非常感谢。你为什么不回答 StackOverflow 的答案?那就不能选你的了。
标签: c++ memory dynamic allocation