繁体   English   中英

C ++类成员初始化和构造函数定义

[英]C++ class member initialization & constructor definition

您好,我开始学习C ++,目前正在测试成员初始化程序,我已经编写了以下简单代码:

#include <iostream>
#include <string>

using namespace std;

class Person
{
public:
    Person();
    ~Person();
private:

    string p_name;
    string p_surname;
    int p_age;

};

Person::Person(string name, string surname, int age) : p_name(name), p_surname(surname), p_age(age)
{


}

Person::~Person()
{
}

class MyClass
{
public:
    MyClass(int value) : m_value(value)
    {
    }
private:
    int m_value;
};

int main()
{
    return 0;
}

但是在Person类中,出现以下错误

错误1错误C2511:'Person :: Person(std :: string,std :: string,int)':在'Person'中找不到重载成员函数c:\\ users \\ syd \\ documents \\ visual studio 2013 \\ projects \\ consoleapplication1 \\ consoleapplication1 \\ consoleapplication1.cpp 19 1 ConsoleApplication1

同样在第二节课中没有错误。 如果我没记错的话,我是在Person类中以错误的方式声明构造函数,而解释器认为我正在重载缺少的方法? 我敢肯定,这样的错误对大多数人来说可能很愚蠢,但是如果有人可以简单地解释我在做什么错,我将不胜感激。

Person()的声明与Person() Person(string name, string surname, int age)的定义不匹配。

在您的班级声明中,将人更改为

public:
  Person(string name, string surname, int age);

您需要将构造函数的原型(带有参数的原型)放在Person类中,而不是将当前没有参数的原型放入

class Person
{
public:
    Person(string name, string surname, int age);
    ~Person();
private:

    string p_name;
    string p_surname;
    int p_age;

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM