小编Dev*_*ull的帖子

静态全局变量和函数内部静态变量的区别

假设我有一个函数,并且我使用该函数内部的void func()变量。testVar另外,我需要变量在离开函数后仍然存在。通常我会通过在函数内部使用静态变量来做到这一点(1)。但是,当我使用全局变量时,有什么区别(2)?

static int testVar = 0; //global variable instead(2)

void func()
{
    static int testVar = 0; //static variable inside of the function(1)

    if(testVar++){
        //do something
    }   
}
Run Code Online (Sandbox Code Playgroud)

编译器在这两种情况下具体做了什么?如果仅需要该变量,是否存在应该使用方法(2)的情况func()

c static global global-variables

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

在同一个函数中使用不同的命

myCout()当我在同一个函数中使用两个不同的命名空间时,为什么我得到错误消息(错误:重载的调用是不明确的)使用using namespace没有完全限定名称空间的指令?

#include <iostream>
using namespace std;

namespace first
{
     void myCout(void)
    {
        cout<<"Hello World is great\n";
    }
}

namespace second
{
     void myCout(void)
    {
        cout<<"Hello Sky is high\n";
    }
}

    int main(void)
    {

        cout<<"Hello World\n";
        using namespace first;
            myCout();

        using namespace second;
            myCout();

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

如果我myCout()在下面给出的第二个命名空间中使用完全限定的命名空间,则没有问题

int main(void)
{
    cout<<"Hello World\n";
    using namespace first;
    myCout();
    second::myCout();
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

c++ oop namespaces function

1
推荐指数
1
解决办法
470
查看次数

将 const char* 分配给 char*

#include <cstring>

char* str0;
const char* str1 = "abc";


// assign str1 to str0
strcpy(str0, str1);    // syntax correct, but run time error
str0 = str1;           // syntax error, cannot convert const char* to char*
string n_str = str1;
str0 = n_str;          // syntax error, cannot convert ...


cout << str0 << endl;  // expected output: abc
Run Code Online (Sandbox Code Playgroud)

我想在运行时(编译后)使 str0 与 str1 相同,我不知道该怎么做。对于这种情况,str0 = str1;我不明白为什么它不起作用,因为 str0 指向任何内容,而 str1 指向一个 const 字符串文字,所以如果我现在让 str0 指向 str1 指向的内容,应该没问题,但事实并非如此。那么有没有办法解决呢?

c++ string pointers

1
推荐指数
1
解决办法
684
查看次数

如何使用带有std :: set的分配器?

我试图使用自己的分配器来测量C++中的内存使用情况std::set.不幸的是,我在链接时遇到错误.为了简化问题,我有以下程序:

#include<set>
#include<vector>
#include<memory>
//using Container = std::vector<int, std::allocator<int>>;
using Container = std::set<int, std::allocator<int>>;

int main() {
  Container container;
  container.push_back(4711);
  container.insert(4711);  
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果可以在wandbox https://wandbox.org/permlink/R5WcgSvSWiqstYxL#wandbox-resultwindow-code-body-1中找到

我试过gcc 6.3.0,gcc 7.1.0,clang 4.0.0和clang 6.0.0HEAD.在所有情况下,我使用a时都会出错std::set,但是当我使用a时却没有std::vector.

如何声明我的设置使用分配器?

我想使用C++ 17,但C++ 14中的答案也很好.

c++ set allocator c++14 c++17

0
推荐指数
1
解决办法
810
查看次数

标签 统计

c++ ×3

allocator ×1

c ×1

c++14 ×1

c++17 ×1

function ×1

global ×1

global-variables ×1

namespaces ×1

oop ×1

pointers ×1

set ×1

static ×1

string ×1