2

如果我们在 C# 中有以下简单代码:

class Program
{
     static void Main(string[] args)
     {
          string x = "Hello World";
          test(x);
          int y = 101;
          test(y);
          Console.ReadKey();
      }

      static void test(object val)
      {
          Console.WriteLine(val);
      }
}  

因此,我们有一个引用类型对象作为参数 - 工作正常。如何在 C++ 中做类似的事情?

OT:无需直接输入,我们可以使用var关键字,在 C++ 中存在关键字auto。这里是否有任何类似的引用类型,如对象或某种方式/技巧来证明它?

4

3 回答 3

3

在 C++ 中,并不是所有的对象都派生自一个通用的基类型。没有通用的运行时多态性。但是,您可能会通过模板使用编译时多态性来获得所需的行为。

#include <iostream>
#include <string>

template <class T> void test(const T& val)
{
    std::cout << val << "\n";
}


int main(int ac, char **av)
{
    std::string x = "Hello World";
    test(x);
    int y = 101;
    test(y);
}
于 2012-10-16T15:35:14.497 回答
1

C++ 没有类似于 C# 的“根类型” System.Object。您可以使用boost::any来模拟这个概念,但这需要使用外部库。

至于通过引用传递参数,您可以在 C++ 中使用MyType &myTypeRef语法通过引用传递,或者通过指针传递MyType *myTypePtr

于 2012-10-16T15:35:02.713 回答
0

因为 C++ 没有为所有类型强制使用一个通用的基类型,所以你不能做完全相同的事情。但是,您可以使用模板来实现相同的目的:

 void fn(....)
 {
      string x = "Hello World";
      test(x);
      int y = 101;
      test(y);
  }

  template <typename T>
  void test(const T& val)
  {
      cout << val;
  }
于 2012-10-16T15:36:26.370 回答