可以在类之外定义构造函数吗?

Can the constructor be defined out of the class?

本文关键字:定义 构造函数      更新时间:2023-10-16

为什么gcc不能成功编译下面的代码?可以在类之外定义构造函数吗?

#include <string>
using std::string;
class Person{
public:
    Person(const string &a, const string &b);
private:
    string name, address;
};
Person::Person(const string &a, const string &b){
    name(a);
    address(b);
}

谢谢!

因为nameaddress都不可调用。您可能打算将它们放入成员初始化列表中。

Person::Person(const string &a, const string &b)
    : name(a), address(b)
{
}

语法错误:

Person::Person(const string &a, const string &b) : name(a), address(b) {}

你写错了。应该是:

Person::Person(const string &a, const string &b) :  name(a), address(b) { }

原则上,并且在实践中,您可以并且应该在类定义之外定义成员函数,以解耦代码库并减少编译时间。

这叫做实现和声明的分离。这实际上是一个好主意保持你的实现分开,在cccpp文件。

因此,在你的标题中:

//Person.h
#ifndef PERSON_H  //  <---- include header guards in your headers
#define PERSON_H
#include <string>
//using std::string; <--- you should remove this line, you don't want to import namespaces
//                        in your header file, or else they are imported in all 
//                        files including this header
class Person{
public:
    Person(const std::string &a, const std::string &b);
private:
    std::string name, address; // qualify your names in the header
};
#endif

和你的实现文件:

//Person.cpp
#include "Person.h"
using namespace std;  //  <---- if you wish, import the std namespace in your global namespace
                      //        in the implementation file
Person::Person(const string &a, const string &b):
    name(a),       // <---- correct syntax of initializer lists 
    address(b)
{
}