2010-10-13 109 views
2

刚刚看到this question与C++类和程序中的段错误问题有关。类中的C++方法定义是否必须指定返回类型?

我的问题涉及类定义。这是因为它被张贴:

class A { 
    int x; 
    int y; 

    public: 
    getSum1() const { 
     return getx() + y; 
    } 

    getSum2() const { 
     return y + getx(); 
    } 

    getx() const { 
     return x; 
    }  
} 

对这个问题的答案都不迄今在关于返回类型的方法的任何提及。我希望他们像

int getSum1() const { .... 
int getSum2() const { .... 
int getx() const { .... 

定义执行int■找在那里?

回答

3

是的,int必须在那里。原始代码示例无效(如其他人提到的代码最初可能是C而不是C++)。首先,类声明需要一个终止分号来代表编译的机会。 G ++报道:

foo.cpp:3: note: (perhaps a semicolon is missing after the definition of ‘A’) 

添加分号,我们得到:

class A { 
    int x; 
    int y; 

public: 
    getSum1() const { 
    return getx() + y; 
    } 

    getSum2() const { 
    return y + getx(); 
    } 

    getx() const { 
    return x; 
    }  
}; 

仍然失败。 g ++会报告如下:

foo.cpp:8: error: ISO C++ forbids declaration of ‘getSum1’ with no type 
foo.cpp:12: error: ISO C++ forbids declaration of ‘getSum2’ with no type 
foo.cpp:16: error: ISO C++ forbids declaration of ‘getx’ with no type 
4

是的,在C++返回类型必须指定。有关C和C++之间的比较,请参阅here

1

是的,他们必须在那里。

相关问题