相关疑难解决方法(0)

为什么我不能在类中初始化非const静态成员或静态数组?

为什么我不能在类中初始化非const static成员或static数组?

class A
{
    static const int a = 3;
    static int b = 3;
    static const int c[2] = { 1, 2 };
    static int d[2] = { 1, 2 };
};

int main()
{
    A a;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器发出以下错误:

g++ main.cpp
main.cpp:4:17: error: ISO C++ forbids in-class initialization of non-const static member ‘b’
main.cpp:5:26: error: a brace-enclosed initializer is not allowed here before ‘{’ token
main.cpp:5:33: error: invalid in-class initialization of static data …
Run Code Online (Sandbox Code Playgroud)

c++ static const

93
推荐指数
3
解决办法
9万
查看次数

尾随返回类型语法样式应该成为新C++ 11程序的默认样式吗?

C++ 11支持新的函数语法:

auto func_name(int x, int y) -> int;
Run Code Online (Sandbox Code Playgroud)

目前此函数将声明为:

int func_name(int x, int y);
Run Code Online (Sandbox Code Playgroud)

新风格似乎还没有被广泛采用(比如在gcc stl中)

但是,这种新风格是否应该在新的C++ 11程序中随处可见,还是仅在需要时使用?

就个人而言,我更喜欢旧款式,但是混合风格的代码库看起来很丑陋.

c++ auto c++11 trailing-return-type

80
推荐指数
4
解决办法
2万
查看次数

C++初始化非常量静态成员变量?

我得到了成员变量'objectCount'的资格错误.编译器还返回'ISO C++禁止非const静态成员的类内初始化'.这是主要类:

#include <iostream>
#include "Tree.h"
using namespace std;

int main()
{
    Tree oak;
    Tree elm;
    Tree pine;

    cout << "**********\noak: " << oak.getObjectCount()<< endl;
    cout << "**********\nelm: " << elm.getObjectCount()<< endl;
    cout << "**********\npine: " << pine.getObjectCount()<< endl;
}
Run Code Online (Sandbox Code Playgroud)

这是包含非const静态objectCount的树类:

#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED

class Tree
{
    private:
        static int objectCount;
    public:
        Tree()
        {
            objectCount++;
        }
        int getObjectCount() const
        {
            return objectCount;
        }
    int Tree::objectCount = 0;
}
#endif // TREE_H_INCLUDED
Run Code Online (Sandbox Code Playgroud)

c++ static const

8
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×3

const ×2

static ×2

auto ×1

c++11 ×1

trailing-return-type ×1