注册 登录
编程论坛 C++教室

类数据成员初始化

easygo 发布于 2016-04-11 18:40, 3629 次点击
类中私有成员是静态字符串的数据成员,要怎样对其初始化呢
6 回复
#2
rjsp2016-04-11 19:49
静态?那定义时给初值呀
我猜你说的是const char[],如果是,根本不需要数组,指针就行了
#3
easygo2016-04-11 20:23
回复 2楼 rjsp
我说的不是const,是static,静态数据成员
#4
alice_usnet2016-04-11 20:42
程序代码:
#include <iostream>
#include<string>
using namespace std;
class a{
public:
  void print(){std::cout<<s<<std::endl;}
private:
    static string s;
};
string a::s;

int main()
{
    a b;
    b.print();
}

字符串对象s会调用string类的默认构造函数。
#5
easygo2016-04-11 21:05
回复 4楼 alice_usnet
那能不能直接    string a::s='abc';
#6
easygo2016-04-11 21:08
我试了试,不行,那要怎么直接初始化
#7
alice_usnet2016-04-11 21:22
程序代码:
#include <iostream>
#include<string>
using namespace std;
class a{
public:
  void print(){std::cout<<s<<std::endl;}
private:
    static string s;
};
string a::s("abc");  //调用string类带参数的构造函数

int main()
{
    a b;
    b.print();
}
1