按照C++ Primer中的讲解static的代码试验,却在编译时出错,求大神指点问出在哪里?
源代码:
#include "stdafx.h"
#include
#include
using namespace std;
class Account{
public:
void applyint() {amount+=amount*interestRate;}
static double rate() {return interestRate;}
//static void rate(double);
private:
string owner;
double amount;
static double interestRate;
static double initRate;
};
void main()
{
Account ac1;
Account *ac2=&ac1;
double rate;
rate=ac1.rate();
/* rate=ac2->rate();
//rate=Account::rate();*/
}
编译错误信息:
1>D:\C++ Primer Practice\static\test1\Debug\test1.exe : fatal error LNK1120: 1 个无法解析的外部命令
http://codepad.org/QWGlZn1J
可以编译。如果你不是vc++ 6,main需要int,不要stdafx.h
看你的样子应该是新建的工程吧,新手的话,建议可以直接新建一个cpp来实验,这样许多书的代码都可以直接输入编译运行。
晚上又折腾了下,问题应该是出在static的变量没有初始化,下面这段代码是OK的。
如果去掉double Account::interestRate=0;则不行。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Account{
public:
void applyint() {amount+=amount*interestRate;}
static double rate() {return interestRate;}
static void rate(double);
private:
string owner;
double amount;
static double interestRate;
static double initRate;
};
double Account::interestRate=0;
void Account::rate(double newrate)
{
interestRate=newrate;
}
void main()
{
Account ac1;
Account *ac2=&ac1;
ac1.rate(0.12);
cout<<ac1.rate()<<endl;
cout<<ac2->rate()<<endl;
cout<<Account::rate()<<endl;
}