小编And*_*ect的帖子

VB.net比C++更快?

可能重复:
为什么C#执行Math.Sqrt()比VB.NET慢?

我遇到了一个有趣的问题,其中我在VB.net中有代码,在C++中有完全相同的代码.我希望C++自然比VB.net运行得更快,但我得到的恰恰相反:VB.net的运行速度是C++的两倍多.程序遍历从1到2,000,000的所有数字,确定它们是否为素数,并将所有素数加在一起.以下是以下片段:

C++

void problem10(void)
{   
   clock_t init, final;
   init=clock();

   int maxVal = 2000000;
   long long sumOfPrimes = 0;
   for (long i = 2; i < maxVal; i++)
   {
      if (isPrime(i))
      {
         sumOfPrimes+= i;
      }
   }
   final = clock() - init;
   cout << (double)final / ((double)CLOCKS_PER_SEC);
   cout << "The sum of all the prime numbers below " << maxVal << " is " << sumOfPrimes;
}

bool isPrime(int NumToCheck)
{
   for (int i = 2; i <= (sqrt((double)NumToCheck)); i++) …
Run Code Online (Sandbox Code Playgroud)

c++ vb.net optimization

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

Java Setter和Constructor混淆

我对如何在Java中使用构造函数和setter感到困惑,请参阅下面的示例代码:

public class Name {
   private String name;

   public void setName(String name){
      this.name=name;
   }  
   public String getName(){
      return name;
   }
}

public static void main(String[] args) {
    Name a=new Name();
    a.setName("123");       
    System.out.println(a.getName());
}
Run Code Online (Sandbox Code Playgroud)

它打印出123,它使用没有构造函数的setter方法,我还编写了下面的其他代码:

public class Name {
   private String name;


   public Name(String nm){
      name=nm;
   }
   public String getName(){
      return name;
   }  
}



public static void main(String[] args) {
   Name a=new Name("123");

   System.out.println(a.getName());

}
Run Code Online (Sandbox Code Playgroud)

这个也打印出123,它是使用没有setter方法的构造函数,这就是为什么我不明白构造函数和setter之间使用的区别,请指教,欢呼!

java setter constructor

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

复制在错误对象上调用的构造函数

我目前正在为Linked List类实现一个拷贝构造函数.当我使用另一个链接列表作为参数创建类的新实例时,正在为我作为参数传递的对象调用构造函数.这让我感到困惑,无法相信.以下是了解主方法中发生的事情所需的部分:

int main()
{
   LinkedList ll;
   LinkedList ll2(ll);
}
Run Code Online (Sandbox Code Playgroud)

因此,不是为ll2调用复制构造函数,而是调用ll的复制构造函数.在我尝试将ll复制到新的LinkedList(即ll2)之前,我已经确认ll的大小正确3.虽然复制之后,两者都具有相同的大小,大于3,但更奇怪的是,ll的复制构造函数被调用,而不是ll2的复制构造函数.由于我使用的是VC++,我已经通过该程序来确认这一点.

这是LinkedList类的复制构造函数:

LinkedList::LinkedList(const LinkedList & other)        
{
   LLNode *otherCurNode = other.GetFirst();
   if (otherCurNode != NULL)
   {
      front = new LLNode(otherCurNode->GetValue(), NULL, NULL);
      back = front;
   }
   else
   {
      front = NULL;
      back = NULL;
   }
   LLNode *curNode = front;
   while (otherCurNode != NULL)
   {
      Insert(otherCurNode->GetValue(), curNode);
      curNode = curNode->GetNext();
      otherCurNode = otherCurNode->GetNext();
      back = curNode;
   }
   numNodes = other.GetSize();
}   
Run Code Online (Sandbox Code Playgroud)

如果这最终成为一个简单的问题我很抱歉 - 我对C++很新.任何帮助将不胜感激!

c++ visual-c++

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

标签 统计

c++ ×2

constructor ×1

java ×1

optimization ×1

setter ×1

vb.net ×1

visual-c++ ×1