首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在*.cpp文件中实现静态类成员函数?

如何在*.cpp文件中实现静态类成员函数?
EN

Stack Overflow用户
提问于 2011-03-21 09:58:50
回答 5查看 159.9K关注 0票数 139

是否可以在*.cpp文件中实现static类成员函数,而不是在头文件中实现?

所有的static函数都是inline

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-03-21 10:04:26

它是。

test.hpp:

代码语言:javascript
复制
class A {
public:
    static int a(int i);
};

test.cpp:

代码语言:javascript
复制
#include <iostream>
#include "test.hpp"


int A::a(int i) {
    return i + 2;
}

using namespace std;
int main() {
    cout << A::a(4) << endl;
}

它们并不总是内联的,不是,但编译器可以生成它们。

票数 168
EN

Stack Overflow用户

发布于 2011-03-21 10:04:13

试试这个:

header.hxx:

代码语言:javascript
复制
class CFoo
{
public: 
    static bool IsThisThingOn();
};

class.cxx:

代码语言:javascript
复制
#include "header.hxx"
bool CFoo::IsThisThingOn() // note: no static keyword here
{
    return true;
}
票数 49
EN

Stack Overflow用户

发布于 2013-08-02 12:55:12

helper.hxx

代码语言:javascript
复制
class helper
{
 public: 
   static void fn1 () 
   { /* defined in header itself */ }

   /* fn2 defined in src file helper.cxx */
   static void fn2(); 
};

helper.cxx

代码语言:javascript
复制
#include "helper.hxx"
void helper::fn2()
{
  /* fn2 defined in helper.cxx */
  /* do something */
}

A.cxx

代码语言:javascript
复制
#include "helper.hxx"
A::foo() {
  helper::fn1(); 
  helper::fn2();
}

要了解c++如何处理静态函数的更多信息,请访问:Are static member functions in c++ copied in multiple translation units?

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5373107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档