简体   繁体   English

在C ++中将局部变量分配给全局变量

[英]assigning local variable to global variable in c++

i have object 我有对象

 template <class FLOAT>
 struct Cstruct {
       Struct1<FLOAT> _var1;
       Struct2<FLOAT> _var2;   
       Cstruct(){};
       Cstruct(Struct1 var1,Struct2 var2):_var1(var1),_var2(var2){};
};

FLOAT can be "double" or "int". FLOAT可以是“ double”或“ int”。 Struct1 and Struct2 are also templatized with FLOAT. Struct1和Struct2也用FLOAT进行模板化。

now i also have a global variable declared 现在我也声明了一个全局变量

 Cstruct<double> globalObj_d;Cstruct<int> globalObj_i;

inside main() i have 在main()内部

main(){
  // some code
  if double then call func<double>();
  if int    then call func<int>();        

}

and inside templatized func() i have 和内部的模板化func()

template<class FLOAT> void func(){
 // some code 
 Struct1<FLOAT> var1;
 Struct2<FLOAT> var2;
 Cstruct<FLOAT> localObj(var1,var2);
 // now i want to assign "localObj" to the global object "globalObj_d"
 if double then 
     globalObj_d = localObj;
 if int then
     globalObj_i = localObj;
} 

and i get an error saying 我得到一个错误的说法

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Cstruct<FLOAT>

does does this mean i have to explicitly write an "operator=" inside Cstruct ? 这是否意味着我必须在Cstruct中显式编写一个“ operator =“? my understading of templatized and global object it seems is kind of flawed. 我对模板化和全局对象的理解似乎有点缺陷。 any help will greatly appreciated. 任何帮助将不胜感激。

In this case you might need to. 在这种情况下,您可能需要这样做。 See the rule of three The compiler will provide one for you if it can. 请参阅三规则。如果可以,编译器将为您提供一个。 You have not showed us the definitions of Struct1<FLOAT> or Struct2<FLOAT> . 您尚未向我们显示Struct1<FLOAT>Struct2<FLOAT> If it can't generate assignments for these, it can't generate one for CStruct . 如果它无法为这些生成赋值,则无法为CStruct生成CStruct

While you are there, avoid the leading underscores on the variable names . 在此期间,请避免在变量名上使用前划线

The use of psudocode in your question make it difficult to understand. 在您的问题中使用伪代码很难理解。 So let me try to boil this down a little bit in to real code. 因此,让我尝试将其归结为实际代码。 It appears that what you are trying to do is essentially something along these lines: 看来您尝试做的事情本质上符合以下几方面:

template <typename VAL>
class Foo
{
public:
  VAL mVal;
};

int main()
{
  Foo <int> global_i;
  Foo <double> global_d;

  Foo <double> local;

  // ...
  if (/*someConditional*/)
    global_i = local;  // <== LINE 1
  else
    global_d = local;  // <== LINE 2
}

This won't work. 这行不通。 Note that even though only one of either LINE1 or LINE2 are executed at run-time, they are both compiled at compile-time. 请注意,即使在运行时仅执行LINE1LINE2之一,它们都在编译时进行编译。 The first one is trying to assign a Foo<int> to a Foo<double> , but the types are not compatible much in the same way that these are also not compatible: 第一个尝试将Foo<int>分配给Foo<double> ,但是类型不兼容,方式与它们也不兼容相同:

class Gee
{
};

class Whiz
{
};

int main()
{
  Gee g;
  Whiz w;

  Gee local;
  local = w;  // <<< INCOMPATIBLE TYPES
}

In order to make this work, you will either need to provide some kind of conversion operator on Foo to convert to another type of Foo , for example: 为了使此工作有效,您要么需要在Foo上提供某种转换操作符,然后才能转换为另一种Foo类型,例如:

template <typename VAL>
class Foo
{
public:
  template <typename OTHER> operator Foo <OTHER> () const 
  {
    Foo <OTHER> ret;
    // ...
    return ret;
   }
};

...or perhaps provide two separate functions to do the assignments; ...或者可能提供两个单独的功能来进行分配; one for a Foo<int> , and another for a Foo<double> . 一个用于Foo<int> ,另一个用于Foo<double>

First: if a type might be either floating point or integer, don't name it "FLOAT". 第一:如果类型可以是浮点数或整数, 则不要将其命名为“ FLOAT”。 You could use the standard T , or perhaps something like Number , but definitely avoid FLOAT . 您可以使用标准T ,也可以使用诸如Number东西,但绝对不要使用FLOAT

As to the real question (or my guess at the real question): almost any time you think in terms of if (type == X) or switch (type) sort of code (at least in C++), you're making a fundamental mistake -- you can probably manage to do that if you want to badly enough, but it's not how C++ is intended to work. 关于真正的问题(或我对真正问题的猜测):几乎任何时候您都在考虑if (type == X)switch (type)类代码(至少在C ++中),基本错误-如果您想做的足够糟糕, 可以设法做到这一点, 但这不是C ++的工作原理。

In this case, there's a fairly easy way to avoid it: create another template. 在这种情况下,有一种避免这种情况的简单方法:创建另一个模板。 In particular, you can overload a couple of function templates, one for each global you want to support: 特别是,您可以重载几个功能模板,每个要支持的全局模板一个:

#include <string>
#include <iostream>

int i_global;
double d_global;

template <class T>
void assign(T in) { 
    // this function should never be called.
    assert(false);
}

template<>
void assign<int>(int in) { 
    i_global = in;
}

template<>
void assign<double>(double in) {
    d_global = in;
}

// for the moment, func(input) will just call assign(input):
template <class T>
void func(T input) {
    assign<T>(input);
}

int main(int argc, char **argv) { 
    if (argc != 2) {
        std::cerr << "Usage: trash <number>\n";
        return EXIT_FAILURE;
    }

    std::string in(argv[1]);

    // see if the input contains a decimal point, and act accordingly:
    if (in.find('.') != std::string::npos)
        func(std::stod(in));
    else
        func(std::stoi(in));

    // show the results -- the values of the globals:
    std::cout << "Result:\ndouble: " << d_global << "\nint: " << i_global << "\n";
    return 0;
}

I get the result I'd hope for -- if I enter something like 1.5 it gets assigned to the double; 我得到了我希望的结果-如果我输入1.5它将被分配给double; if I enter something like 123 it gets assigned to the int . 如果我输入类似123它将被分配给int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM