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

初学C++中遇到的问题

白杨树cy 发布于 2008-11-22 09:49, 506 次点击
下面定义一个简单类Account,这个类记录一个账号和关于这个账号的款额.可以对这个类进行的操作是存款,取款,查看余额,取账号等.下面是程序代码:
account.h
class Account{
public:
    Account(int id,float amount=0);
    float GetBalance(){return balance;}
    void Save(float amount);
    bool Withdraw(float amount);
    int GetAccountID(){return accountID;}
private:
    int accountID;
    float balance;
};
account.cpp*************************
# include "account.h"
inline Account::Account(int id,float amount)
{
    accountID=id;
    balance=amount;
}
inline void Account::Save(float amount)
{
    balance+=amount;
}
bool Account::Withdraw(float amount)
{
    if(balance<amount)
        return false;
    balance-=amount;
    return true;
}
main.cpp***************************
#include <iostream.h>
#include "account.h"
void main()
{

    Account a(1,100.0);
}
main.cpp进行编译无错误,可是进行连接时就出错了错误代码如下:
------------Configuration: main - Win32 Debug--------------------
Linking...
main.obj : error LNK2001: unresolved external symbol "public: __thiscall Account::Account(int,float)" (??0Account@@QAE@HM@Z)
Debug/main.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.

main.exe - 2 error(s), 0 warning(s)
2 回复
#2
ldy12042008-11-22 13:31
把构造函数里面的inline去掉就好了
#3
debroa7232008-11-22 15:21
inline Account::Account(int id,float amount)
inline void Account::Save(float amount)
类的内联函数不要写到CPP文件中.
内联函数就是把函数在调用的地方,用代码展开的形式,代替原代码,是发生在编译期,而CPP文件是在LINK的时候才用到,所以在编译时,找不到上面两个函数的实现代码,无法展开替换,就被认为没有定义,在LINK的时候,就报出找不到这两个函数的定义.
inline函数是可以放到CPP文件中,但如果这样做,就只能在该CPP文件中使用,如果想在其它文件中使用,就必须在其它文件中拷贝一份,就是说main.cpp文件中代码如下,这样并不划算.
inline void Account::Save(float amount)
{
    balance+=amount;
}
inline Account::Account(int id,float amount)
{
    accountID=id;
    balance=amount;
}
int _tmain(int argc, _TCHAR* argv[])
{
    std::vector< string >::iterator iter1  ;
    std::vector< string >::iterator iter2  ;
    print( iter1 , iter2 ) ;
    int i[3] ;
    int b[3] ;
    print( i ,b ) ;
    Account a(1,100.0f);
    a.Save(2.0f);

    return 0;
}
1